package cc.rengu.redp.bizimpl.upmp.controller;
import cc.rengu.igas.momp.facade.bean.*;
import cc.rengu.igas.momp.facade.request.QueryBankToClientMcStatRequest;
import cc.rengu.igas.momp.facade.request.QueryCouponDetailRequest;
import cc.rengu.igas.momp.facade.request.QueryMcListInfoRequest;
import cc.rengu.igas.momp.facade.request.QueryMcMerUserListRequest;
import cc.rengu.redp.bizimpl.upmp.bean.CommissionAddMchntRequest;
import cc.rengu.redp.bizimpl.upmp.bean.MarketManagerRequest;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpSysParam;
import cc.rengu.redp.bizimpl.upmp.service.CommissionMarketService;
import cc.rengu.redp.bizimpl.upmp.service.CustomerMarketService;
import cc.rengu.redp.bizimpl.upmp.service.ICustomerMarketService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpSysParamService;
import cc.rengu.redp.bizimpl.upmp.vo.CustomerMcInfoVO;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "营销管理:银行对客营销活动管理")
@RestController
@RequestMapping("/admin/market/customerManager")
public class CustomerMarketManagerController {

    public static Logger log = LoggerFactory.getLogger(CustomerMarketManagerController.class);

    @Autowired
    private IUpmpSysParamService upmpSysParamService;

    @Autowired
    private ICustomerMarketService marketService;
    @Autowired
    private CommissionMarketService commissionMarketService;



    //查询营销活动
    @GetMapping("/list")
    @ResponseBody
    public IPage<McListInfoBean> findByPage(QueryRequest pageable,QueryMcListInfoRequest reqDto) throws RedpException {
        reqDto.setQueryType("0");
        reqDto.setQueryRole("00");
        if (StringUtils.isBlank(reqDto.getMcType())) {
            reqDto.setMcType("90");
        }
        return marketService.findMcByPage(pageable, reqDto);
    }

    //增加营销活动
    @GetMapping("/add")
    public Map<String, Object> addShow() {
        Map<String, Object> map=new HashMap<>();
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        UpmpSysParam dict =upmpSysParamService.findByPrimaryKey("marketKbinProdFlag",user.getInstId(),null);
        if(Common.isNotBlank(dict)){
            map.put("marketKbinProdFlag",dict.getPrimaryValue());
        }
        dict=upmpSysParamService.findByPrimaryKey("marketOrgSelectedFlag",user.getInstId(),null);
        if(Common.isNotBlank(dict)){
            map.put("marketOrgSelectedFlag",dict.getPrimaryValue());
        }
        dict=upmpSysParamService.findByPrimaryKey("sealLevelFlag",user.getInstId(),null);
        if(Common.isNotBlank(dict)){
            map.put("sealLevelFlag",dict.getPrimaryValue());
        }
        dict=upmpSysParamService.findByPrimaryKey("marketPlatform",user.getInstId(),null);
        if(Common.isNotBlank(dict)){
            map.put("marketPlatform",dict.getPrimaryValue());
        }
        return map;
    }

    //修改营销活动
    @GetMapping("/edit")
    public  Map<String, Object> editShow(HttpServletRequest request) throws RedpException {
        Map<String, Object> map=new HashMap<>();
        String mcNo = request.getParameter("mcNo");
        String mcType = request.getParameter("mcType");
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        UpmpSysParam dict=upmpSysParamService.findByPrimaryKey("marketKbinProdFlag",user.getInstId(),null);
        if(Common.isNotBlank(dict)){
            map.put("marketKbinProdFlag",dict.getPrimaryValue());
        }
        dict=upmpSysParamService.findByPrimaryKey("sealLevelFlag",user.getInstId(),null);
        if(Common.isNotBlank(dict)){
            map.put("sealLevelFlag",dict.getPrimaryValue());
        }
        dict=upmpSysParamService.findByPrimaryKey("marketPlatform",user.getInstId(),null);
        if(Common.isNotBlank(dict)){
            map.put("marketPlatform",dict.getPrimaryValue());
        }
        if (StringUtils.isBlank(mcNo)) {
            log.error("营销活动编号不能为空");
            throw new RedpException("营销活动编号不能为空");
        }
        if ("00".equals(mcType) || "01".equals(mcType) || "02".equals(mcType) || "03".equals(mcType)) {
            marketService.setMoneyOffMcModel(map, mcNo, "0", "00");
        } else if ("10".equals(mcType) || "11".equals(mcType)) {
            marketService.setCouponMcModel(map, mcNo, "0", "00");
        } else {
            log.error("请求参数有误,营销活动类型的值无效,mcType=[{}]", mcType);
            throw new RedpException("请求参数有误,营销活动类型的值无效，请联系管理员");
        }
        List<McMchntInfoBean> circleList = marketService.getMchntCircleList(mcNo, "-1", "-1");
        map.put("circleList", circleList);
        return map;
    }


    //银行对客营销活动管理:修改  银行对客营销活动管理:新增
    @PostMapping("/add")
    @ResponseBody
    public OperationResult editSave(HttpServletRequest request, CustomerMcInfoVO entity) throws RedpException {
        if (StringUtils.isBlank(entity.getMcMethod())) {
            String mcMethod = request.getParameter("mcMethodHidden");
            entity.setMcMethod(mcMethod);
        }
        //判断操作类型
        String msg = "保存草稿成功！";
        if ("1".equals(entity.getOprType())) {
            msg = "提交成功，等待审核员通过后由发布员发布！";
        }
        entity.setQueryType("0");
        entity.setQueryRole("00");
        List<String> onLineProduce = entity.getOnLineProduce();
        List<String> upLineProduce = entity.getUpLineProduce();
        for(int i=0;i<onLineProduce.size();i++){
            String onProd= (String) onLineProduce.get(i);
            if("PM003000".equals(onProd) ||"PM003010".equals(onProd) ||"PM003020".equals(onProd) ||"PM003030".equals(onProd)){
                for(int j=0;j<upLineProduce.size();j++){
                    String upProd=(String)upLineProduce.get(j);
                    if(upProd.equals(onProd)){
                        upLineProduce.remove(upLineProduce.get(j));
                        break;
                    }
                }
            }
        }
        entity.setOnLineProduce(onLineProduce);
        entity.setUpLineProduce(upLineProduce);
        //判断减免类还是卡券类
        if ("0".equals(entity.getMcMethod())) {
            marketService.editMoneyOffMcSave(entity);
        } else if ("1".equals(entity.getMcMethod())) {
            marketService.editCouponMcSave(entity);
        } else {
            log.error("请求参数有误,优惠方式为减免优惠还是优惠券的值无效,mcMethod=[{}]", entity.getMcMethod());
            throw new RedpException("请求参数有误，请联系管理员");
        }
        return OperationResult.buildSuccessResult(msg);
    }

    //删除营销活动
    @PostMapping( "/delete")
    @ResponseBody
    public OperationResult deleteSubmit(MarketManagerRequest entity) throws RedpException {
        if (StringUtils.isBlank(entity.getMcNo())) {
            throw new RedpException("营销活动编号不能为空");
        }
        entity.setOprType("0");
        entity.setMsg("对客营销活动删除");
        entity.setQueryType("0");
        entity.setQueryRole("00");
        if ("00".equals(entity.getMcType()) || "01".equals(entity.getMcType()) || "02".equals(entity.getMcType()) || "03".equals(entity.getMcType())) {
            marketService.manageMoneyOffMc(entity);
        } else if ("10".equals(entity.getMcType()) || "11".equals(entity.getMcType())) {
            marketService.manageCouponMc(entity);
        } else {
            log.error("请求参数有误,营销活动类型的值无效,mcType=[{}]", entity.getMcType());
            throw new RedpException("请求参数有误,营销活动类型的值无效，请联系管理员");
        }
        return OperationResult.buildSuccessResult("对客营销活动删除成功");
    }

    //增加商户
    @GetMapping("/addMerchant")
    public Map<String, Object> addMerchantShow(Map<String, Object> map, HttpServletRequest request) throws RedpException {
        String mcNo = request.getParameter("mcNo");
        String mcType = request.getParameter("mcType");
        if (StringUtils.isBlank(mcNo)) {
            log.error("营销活动编号不能为空");
            throw new RedpException("营销活动编号不能为空");
        }
        if ("00".equals(mcType) || "01".equals(mcType) || "02".equals(mcType) || "03".equals(mcType)) {
            marketService.setMoneyOffMcModel(map, mcNo, "0", "00");
        } else if ("10".equals(mcType) || "11".equals(mcType)) {
            marketService.setCouponMcModel(map, mcNo, "0", "00");
        } else {
            log.error("请求参数有误,营销活动类型的值无效,mcType=[{}]", mcType);
            throw new RedpException("请求参数有误,营销活动类型的值无效，请联系管理员");
        }
        map.put("circleList", marketService.getMchntCircleList(mcNo, "-1", "-1"));
        return map;
    }

    //添加营销活动 进行中增加商户
    @PostMapping("/addMerchant")
    @ResponseBody
    public OperationResult addMerchantSave(CommissionAddMchntRequest entity) throws RedpException {
        if (StringUtils.isBlank(entity.getMerchantList()) && StringUtils.isBlank(entity.getCircleList())) {
            log.error("商户或者商圈不能为空");
            throw new RedpException("商户或者商圈不能为空");
        }
        if (StringUtils.isBlank(entity.getMcNo())) {
            log.error("活动编码不能为空");
            throw new RedpException("活动编码不能为空");
        }
        entity.setQueryType("0");
        entity.setQueryRole("00");
        return commissionMarketService.addmchntInfos(entity);
        //return OperationResult.buildSuccessResult("进行中的活动新增商户成功");
    }

    /**
     * 详情
     * flag=viewManager  管理详情页面
     * flag=chkView      审核详情页面
     * flag=check        审核页面
     * flag=rlaView      发布详情页面
     * flag=release      发布页面
     * flag=pause        暂停页面
     * flag=shutdown     终止页面
     * flag=resume       启用页面
     */
    @GetMapping("/view")
    public Map<String, Object> viewShow(HttpServletRequest request) throws RedpException {
        Map<String, Object> result = new HashMap<>();
        String queryType = "0";
        String queryRole = "00";
        String flag = request.getParameter("flag");
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        UpmpSysParam dict = upmpSysParamService.findByPrimaryKey("marketKbinProdFlag",user.getInstId(),null);
        if(Common.isNotBlank(dict)){
            result.put("marketKbinProdFlag",dict.getPrimaryValue());
        }
        dict=upmpSysParamService.findByPrimaryKey("sealLevelFlag",user.getInstId(),null);
        if(Common.isNotBlank(dict)){
            result.put("sealLevelFlag",dict.getPrimaryValue());
        }
        //802行点选营销活动“发布”按钮后该活动直接发布，无须确认是否打款这一环节
        dict=upmpSysParamService.findByPrimaryKey("skipPub",user.getInstId(),null);
        if(Common.isNotBlank(dict)){
            result.put("skipPub",dict.getPrimaryValue());
        }
        if ("chkView".equals(flag) || "check".equals(flag)) {
            queryRole = "01";
        } else if ("rlaView".equals(flag) || "release".equals(flag) || "pause".equals(flag) || "shutdown".equals(flag) || "resume".equals(flag)) {
            queryRole = "02";
        } else {
            log.info("CustomerMarketManagerController:viewShow");
        }
        result.put("flag", flag);
        String mcNo = request.getParameter("mcNo");
        String mcType = request.getParameter("mcType");
        if (StringUtils.isBlank(mcNo)) {
            log.error("营销活动编号不能为空");
            throw new RedpException("营销活动编号不能为空");
        }
        if ("00".equals(mcType) || "01".equals(mcType) || "02".equals(mcType) || "03".equals(mcType)) {
            marketService.setMoneyOffMcModel(result, mcNo, queryType, queryRole);
        } else if ("10".equals(mcType) || "11".equals(mcType)) {
            marketService.setCouponMcModel(result, mcNo, queryType, queryRole);
        } else {
            log.error("请求参数有误,营销活动类型的值无效,mcType=[{}]", mcType);
            throw new RedpException("请求参数有误,营销活动类型的值无效，请联系管理员");
        }
        request.setAttribute("mcNo",mcNo);

        result.put("circleList", marketService.getMchntCircleList(mcNo, "-1", "-1"));
        return result;
    }

    //查询卡券活动概览明细
    @GetMapping("/detailViewList")
    @ResponseBody
    public IPage<CouponListInfoBean> findDetailDatasByPage(QueryRequest pageable,QueryCouponDetailRequest reqDto, HttpServletRequest request) throws RedpException {
        reqDto.setQueryType("0");
        reqDto.setQueryRole("00");
        return marketService.findCouponDetailByPage(reqDto, pageable);
    }

    //银行对客营销活动管理:活动报表
    @GetMapping("/report")
    public String reportShow(HttpServletRequest request, Model model, QueryBankToClientMcStatRequest reqDto,QueryRequest pageable) throws RedpException {
        reqDto.setQueryType("0");
        reqDto.setQueryRole("00");
        reqDto.setPageIndex(String.valueOf(pageable.getPageNum()));
        reqDto.setPageSize(String.valueOf(pageable.getPageSize()));

        BankToClientMcStatInfoBean bean = marketService.reportActivity(reqDto);
        List<BankToClientMcTxnStatInfoBean> txnStatInfoList = bean.getTxnStatInfoList();
        List<String> xAxisData = new ArrayList<>();
        List<String> yAxismcMchntQtyData = new ArrayList<>();
        List<String> yAxisoriginalMchntQtyData = new ArrayList<>();
        List<String> yAxismcMchntAmtData = new ArrayList<>();
        List<String> yAxisoriginalMchntAmtData = new ArrayList<>();
        if (null != txnStatInfoList) {
            for (BankToClientMcTxnStatInfoBean statInfobean : txnStatInfoList) {
                xAxisData.add(statInfobean.getTxnDate());
                yAxismcMchntQtyData.add(statInfobean.getMcMchntQty());
                yAxisoriginalMchntQtyData.add(statInfobean.getOriginalMchntQty());
                yAxismcMchntAmtData.add(statInfobean.getMcMchntAmt());
                yAxisoriginalMchntAmtData.add(statInfobean.getOriginalMchntAmt());
            }
        }

        model.addAttribute("entity", bean);
        model.addAttribute("xAxisData", xAxisData);
        model.addAttribute("yAxismcMchntQtyData", yAxismcMchntQtyData);
        model.addAttribute("yAxisoriginalMchntQtyData", yAxisoriginalMchntQtyData);
        model.addAttribute("yAxismcMchntAmtData", yAxismcMchntAmtData);
        model.addAttribute("yAxisoriginalMchntAmtData", yAxisoriginalMchntAmtData);

        return "/admin/market/customer/csManager-inputReportBasic";
    }
    public List<String> arrToList(String[] arr){
        ArrayList<String> result=new ArrayList<String>();
        if(arr != null) {
            for (int i = 0; i < arr.length; i++) {
                result.add(arr[i]);
            }
        }
        return result;
    }
    public String[] ListToArr(List<String> list){
        String[] result=new String[list.size()];
        for(int i=0;i<list.size();i++){
            result[i]=list.get(i);
        }
        return result;
    }


    /**
     * 跳转到导入的商户信息展示页
     * @param model
     * @param request
     * @return
     */
    @GetMapping("/toMchntList")
    public String toMchntList(Model model, HttpServletRequest request) {
        String deleteMchntList = request.getParameter("deleteMchntList");
        String mcNo = request.getParameter("mcNo");
        String type = request.getParameter("type");
        String deleteId = request.getParameter("deleteId");
        request.setAttribute("deleteMchntList", deleteMchntList);
        request.setAttribute("mcNo", mcNo);
        request.setAttribute("type", type);
        request.setAttribute("deleteId", deleteId);
        request.setAttribute("margin", "view".equals(type) ? "654" : "446");
        return "/admin/market/customer/csManager-mchntList";
    }

    /**
     * 导入的商户信息展示页查询
     *
     * @param request
     * @param reqDto
     * @return
     */
    @GetMapping("/getMchntList")
    @ResponseBody
    public IPage<McMchntInfoBean> getMchntList(HttpServletRequest request, QueryMcMerUserListRequest reqDto,QueryRequest pageable) throws RedpException {
        reqDto.setQueryType("0");
        reqDto.setQueryRole("00");
        reqDto.setMcNo(request.getParameter("mcNo"));
        reqDto.setMchntNo(request.getParameter("mchntNo"));
        return marketService.getMchntList(reqDto, "-1", "-1");
    }



    /**
     * 下载模板
     * type=0:mchntNoBatchImportTemplate
     * type=1:mobilePhoneBatchImportTemplate
     * type=2:cardNoBatchImportTemplate
     */
/*    @MenuData("营销管理:银行对客营销活动管理")
    @RequiresPermissions("营销管理:银行对客营销活动管理")
    @RequestMapping(value = "/downloadExcel", method = RequestMethod.GET)
    public void downloadExcel(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String type = request.getParameter("type");
        String file = "mchntNoBatchImportTemplate.xls";
        if ("1".equals(type)) {
            file = "mobilePhoneBatchImportTemplate.xls";
        } else if ("2".equals(type)) {
            file = "cardNoBatchImportTemplate.xls";
        } else {
            log.info("CustomerMarketManagerController:downloadExcel");
        }
        ExcelDownload.getExcel(request, response, file);
    }*/

    /**
     * 导入手机号和银行卡卡号
     *
     * @param excelFile
     * @param type
     * @return
     * @throws Exception
     */
/*    @MenuData("营销管理:银行对客营销活动管理")
    @RequiresPermissions("营销管理:银行对客营销活动管理")
    @RequestMapping(value = "/uploadUserInfo", method = RequestMethod.POST)
    @ResponseBody
    public OperationResult getDataFromExcel(@RequestParam(value = "excelFile", required = false) MultipartFile excelFile, @RequestParam(value = "type", required = false) String type) throws Exception {
        if (excelFile == null) {
            log.error("请选择文件");
            return OperationResult.buildFailureResult("请选择文件");
        }
        String originalFilename = excelFile.getOriginalFilename();
        if (!originalFilename.endsWith(".xls") && !originalFilename.endsWith(".xlsx")) {
            log.error("文件不是excel类型");
            return OperationResult.buildFailureResult("文件不是excel类型");
        }
        List<String> list = new ArrayList<>();
        Workbook workbook = null;
        if (originalFilename.endsWith(".xlsx")) {
            workbook = new XSSFWorkbook(excelFile.getInputStream());
        } else if (originalFilename.endsWith(".xls")) {
            workbook = new HSSFWorkbook(excelFile.getInputStream());
        } else {
            log.info("CustomerMarketManagerController:getDataFromExcel");
        }
        Sheet sheetAt = workbook.getSheetAt(0);
        int lastRowNum = sheetAt.getLastRowNum();
        if (lastRowNum > 500) {
            return OperationResult.buildFailureResult("上传数据不能超过500行");
        }
        if (lastRowNum < 1) {
            return OperationResult.buildFailureResult("请填入上传的数据");
        }

        if ("1".equals(type)) {
            for (int i = 1; i <= lastRowNum; i++) {
                Row rowTitle = sheetAt.getRow(i);
                if (rowTitle != null) {// 行不为空
                    Cell cell = rowTitle.getCell(0);
                    if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) {
                        if (cell.getCellType() != Cell.CELL_TYPE_STRING) {
                            return OperationResult.buildFailureResult("请将上传文件数据的格式设置为文本格式");
                        }

                        String str = CommonUtils.getValue(cell);
                        String regValidRst = StringValicationUtil.validate(ValidatMethodEnum.CHECK_PHONE, str);
                        if (StringUtils.isNotBlank(regValidRst)) {
                            return OperationResult.buildFailureResult("上传文件的第" + i + "行手机号无效");
                        }
                        list.add(str);
                    }
                }
            }
            // 去重
            list = list.stream().distinct().collect(Collectors.toList());
            return OperationResult.buildSuccessResult("导入文件成功", list);
        }

        for (int i = 1; i <= lastRowNum; i++) {
            Row rowTitle = sheetAt.getRow(i);
            if (rowTitle != null) {// 行不为空
                Cell cell = rowTitle.getCell(0);
                if (cell != null) {
                    if (cell.getCellType() != Cell.CELL_TYPE_STRING) {
                        return OperationResult.buildFailureResult("请将上传文件数据的格式设置为文本格式");
                    }

                    String str = CommonUtils.getValue(cell);
                    if (StringUtils.isNotBlank(str) && (str.length() < 16 || str.length() > 19)) {
                        return OperationResult.buildFailureResult("上传文件的第" + i + "行卡号长度无效");
                    }
                    list.add(str);
                }
            }
        }
        // 去重
        list = list.stream().distinct().collect(Collectors.toList());
        return OperationResult.buildSuccessResult("导入文件成功", list);
    }*/
}
